<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use app\validate\CheckCourse;
use think\exception\ValidateException;


// 课程列表
class Course extends BaseController
{
    public function index()
    {

        $type = config('app.course.type');
        $module = config('app.course.module');
        $seminar_topic = Db::name('seminar_type')->where('status', '=', 1)->order('sort asc')->field('id, e_title')->select();
        $english = config('app.course.english');
        $prerequisite = Db::name('course')->where('status', '=', 1)->field('courseid, e_seminar')->select();

        View::assign('type', $type);
        View::assign('module', $module);
        View::assign('seminar_topic', $seminar_topic);
        View::assign('english', $english);
        View::assign('prerequisite', $prerequisite);
        return View::fetch();
    }



    //+列表信息获取
    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['type', '=', $get['type']];
            }
        }


        if (isset($get['module'])) {
            if (!empty($get['module'])) {
                $where[] = ['module', '=', $get['module']];
            }
        }


        if (isset($get['seminar_topic'])) {
            if (!empty($get['seminar_topic'])) {
                $where[] = ['seminar_topic', '=', $get['seminar_topic']];
            }
        }


        if (isset($get['english'])) {
            if (!empty($get['english'])) {
                $where[] = ['english', '=', $get['english']];
            }
        }


        if (isset($get['prerequisite'])) {
            if (!empty($get['prerequisite'])) {
                $where[] = ['prerequisite', '=', $get['prerequisite']];
            }
        }


        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['seminar|e_seminar|courseid', 'like', '%'.$get['keys'].'%'];
            }
        }


        $where[] = ['status', '=', 1];


        $total = Db::name('course')
            ->where($where)
            ->count();

        $rows = Db::name('course')
            ->where($where)
            ->field('id, courseid, seminar, e_seminar, type, seminar_topic, english, level, module, status, target_level, add_time')
            ->order('add_time', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $v['seminar'] = $v['seminar'] == '' ? $v['e_seminar'] : $v['seminar'];
            $v['seminar_topic'] = get_info($v['seminar_topic'], 'seminar_type', 'e_title');
            $v['type_name'] = get_config('app.course.type', $v['type']);
            $v['module_name'] = get_config('app.course.module', $v['module']);
            $v['english_name'] =  $v['english'] == '' ? '': get_config('app.course.english', $v['english']);
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $type = config('app.course.type');
        $level = config('app.course.level3');
        $seminar_topic = Db::name('seminar_type')->where('status', '=', 1)->order('sort asc')->field('id, e_title')->select();
        $english = config('app.course.english3');
        //自动生成 课程id
        View::assign('courseid', $this->createrCourseId());
        View::assign('type', $type);
        View::assign('level', $level);
        View::assign('seminar_topic', $seminar_topic);
        View::assign('english', $english);

        $data = Db::name('Course')
            ->where('status', '=', 1)
            ->field('courseid, e_seminar')->select();
        View::assign('data', $data);
        return View::fetch();
    }

    protected function createrCourseId(){
        $num = rand(1, 9999999);

        if (7 - strlen($num) > 0) {
            $num = str_pad('',7-strlen($num),0) . $num;
        }
        $res = Db::name('course')->where('courseid')->find();
        if ($res) {
            $num = $this->createrCourseId();
        }
        return $num;
    }



    //+课程保存
    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCourse::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        //唯一
        $cid = Db::name('course')->where('courseid', '=', $post['courseid'])->find();
        if ($cid) {
            return $this->outputAjax('课程ID已存在！');
        }

        try {

            $insert = array(
                'seminar'           => $post['seminar'],
                'e_seminar'         => $post['e_seminar'],
                'img'               => $post['img'],
                //'video'             => $post['video'],
                'courseid'          => $post['courseid'],
                'type'              => $post['type'],
                'seminar_topic'     => $post['seminar_topic'],
                'english'           => $post['english'],
                'target_audience'   => $post['target_audience'],
                'prerequisite'      => $post['prerequisite'],
                'related'           => $post['related'],
                'level'             => $post['level'],
                'days'              => $post['days'],
                'description'       => $post['description'],
                'add_time'          => time(),
                'update_time'       => time()
            );

            if (!Db::name('course')->insert($insert)) {
                return $this->outputAjax('创建失败！');
            }

            return $this->outputAjax('创建成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('course')->find($id);

        //先修课程
        if (empty($inf['prerequisite'])) {
            $inf['prerequisite'] = 0;
        }

        //+相关课程
        if (!empty($inf['related'])) {
            $related = Db::name('course')->where('courseid', 'in', $inf['related'])->field('e_seminar, courseid')->select()->toArray();
            $inf['related'] = $related;
        } else {
            $inf['related'] = [];
        }
        $type = config('app.course.type');
        $level = config('app.course.level3');
        $seminar_topic = Db::name('seminar_type')->where('status', '=', 1)->order('sort asc')->field('id, e_title')->select()->toArray();
        $english = config('app.course.english3');
        View::assign('type', $type);
        View::assign('level', $level);
        View::assign('seminar_topic', $seminar_topic);
        View::assign('english', $english);

        $data = Db::name('Course')
            ->where('status', '=', 1)
            ->field('courseid, e_seminar')->select()->toArray();
        View::assign('data', $data);

        View::assign('inf',$inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCourse::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {

            $course = Db::name('course')->where('id', '=', $post['id'])->find();

            if (!$course) {
                return $this->outputAjax('参数错误！');
            }

            //唯一
            $cid = Db::name('Course')->where('courseid', '=', $post['courseid'])->where('id', '<>', $post['id'])->find();
            if ($cid) {
                return $this->outputAjax('课程ID已存在！');
            }

            $update = array(
                'id'                => $post['id'],
                'seminar'           => $post['seminar'],
                'e_seminar'         => $post['e_seminar'],
                'img'               => $post['img'],
                //'video'             => $post['video'],
                'courseid'          => $post['courseid'],
                'type'              => $post['type'],
                'seminar_topic'     => $post['seminar_topic'],
                'english'           => $post['english'],
                'target_audience'   => $post['target_audience'],
                'prerequisite'      => $post['prerequisite'],
                'related'           => $post['related'],
                'level'             => $post['level'],
                'days'              => $post['days'],
                'description'       => $post['description'],
                'update_time'       => time()
            );

            if (!Db::name('course')->update($update)) {
                return $this->outputAjax('保存失败！');
            }

            return $this->outputAjax('保存成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function delete(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        if(!$id) {
            return $this->outputAjax('参数不足！');
        }

        $ids = explode(',', $id);

        Db::startTrans();

        try {
            foreach ($ids as $key => $value) {

                $courseid = Db::name('course')->where('id', '=', $value)->value('courseid');
                if (empty($courseid)) {
                    return $this->outputAjax('参数错误！');
                }

                $classes = Db::name('classes')->where('courseid', '=', $courseid)->find();

                if (!empty($classes)) {
                    if (!Db::name('classes')->where('courseid', '=', $courseid)->update(['status' => 3])) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[1]！');
                    }
                }


                $class_user = Db::name('classes_user')->where('courseid', '=', $courseid)->find();

                if (!empty($class_user)) {
                    if (!Db::name('classes_user')->where('courseid', '=', $courseid)->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[2]！');
                    }
                }

                $flex_course = Db::name('flex_course')->where('courseid', '=', $courseid)->find();

                if (!empty($flex_course)) {
                    if (!Db::name('flex_course')->where('courseid', '=', $courseid)->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[3]！');
                    }
                }

                $flex_user = Db::name('flex_user')->where('courseid', '=', $courseid)->find();

                if (!empty($flex_user)) {
                    if (!Db::name('flex_user')->where('courseid', '=', $courseid)->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[4]！');
                    }
                }

                if (!Db::name('course')->where('id', '=', $value)->update(['status' => 3])) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[5]！');
                }
                Db::commit();
            }

            return $this->outputAjax('删除成功！', 0);

        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function import()
    {
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $type = config('app.course.type');
            $level = config('app.course.level');
            $english = config('app.course.english');
            $module = config('app.course.module');
            $i = 0;
            foreach ($result['data'] as $key => $value) {
                if (empty($value['e_seminar_type']) || empty($value['courseid']) || empty($value['type']) || $value['courseid'] == 'TBC') {
                    continue;
                }
                if (Db::name('course')->where('courseid', '=', $value['courseid'])->find()) {
                    continue;
                }

                $temp = [];
                $temp['courseid'] = $value[4]; //courseid
                $temp['seminar'] = $value[3]; //'seminar'
                $temp['e_seminar'] = $value[2]; // 'e_seminar'
                $temp['description'] = $value[11]; //'description'
                $temp['e_description'] = $value[12]; // e_description
                $temp['type'] = array_search($value[6],$type);

                if (empty($value[7])) {
                    $temp['days'] = 0;
                } else {
                    $temp['days'] = $value[7];
                }

                if(!empty($value[13]))  {
                    $temp['seminar_owner'] = $value[13];
                    $temp['seminar_owner_name'] = Db::name('members')->where('userid', '=', $value[13])->value('name');
                }

                $temp['seminar_topic'] = Db::name('seminar_type')->where('e_title', '=', $value['e_seminar_type'])->value('id');

                if ($value[9] == '' || array_search(ucfirst(trim($value[9])),$english) || empty($value[9])) {
                    $temp['language'] = 1;
                    $temp['english'] = 4;
                }else{
                    $temp['language'] = 2;
                    $temp['english'] = array_search(ucfirst($value[9]),$english);
                }

                $temp['target_audience'] = $value[10];
                if (empty($value[5])) {
                    $temp['level'] = 5;
                }else{
                    $temp['level'] = array_search($value[5],$level);
                }

                if (empty($value[8])) {
                    $temp['module'] = 7;
                }else{
                    $temp['module'] = array_search($value[8],$module);
                }

                if (empty($value[14])) {
                    $temp['prerequisite'] = '';
                } else {
                    $temp['prerequisite'] = $value[14];
                }

                if ('hot' == strtolower($value[15])) {
                    $temp['hot'] =1;
                }
                if ('new' == strtolower($value[15])) {
                    $temp['latset'] =1;
                }

                $temp['add_time'] = time();
                $temp['update_time'] = time();
                $f = Db::name('course')->insert($temp);
                if ($f) {
                    $i++;
                }
            }

            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }

    // 导出
    public function export(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();
        $where = [];

        if (!empty($get['type'])) {
            $where[] = ['type', '=', $get['type']];
        }

        if (!empty($get['module'])) {
            $where[] = ['module', '=', $get['module']];
        }

        if (!empty($get['seminar_topic'])) {
            $where[] = ['seminar_topic', '=', $get['seminar_topic']];
        }

        if (!empty($get['english'])) {
            $where[] = ['english', '=', $get['english']];
        }

        if (!empty($get['prerequisite'])) {
            $where[] = ['prerequisite', '=', $get['prerequisite']];
        }

        if (!empty($get['keys'])) {
            $where[] = ['seminar|e_seminar|courseid', 'like', '%'.$get['keys'].'%'];
        }


        $where[] = ['status', '=', 1];

        ob_end_clean();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课程数据' . date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['Practice EN', 'Practice CN', 'Seminar EN', 'Seminar CN', 'Code', 'Level', 'Type', 'Days', 'Module', 'Language', 'Target Description', 'Description CN', 'Description EN', 'Owner', 'Prerequisite', 'Recommendation']);

        $total = Db::name('course')
            ->where($where)
            ->count();
        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('course')
                ->where($where)
                ->order('add_time desc')
                ->limit($start, $nums)
                ->select()->toArray();

            foreach ($rows as $value) {
                if ($value['latset'] == 1) {
                    $recommendation = 'new';
                }elseif ($value['hot'] == 1) {
                    $recommendation = 'hot';
                }else{
                    $recommendation = '';
                }

                $arr = [
                    get_info($value['seminar_topic'],'seminar_type','e_title'),
                    get_info($value['seminar_topic'],'seminar_type','title'),
                    $value['seminar'],
                    $value['e_seminar'],
                    $value['courseid'],
                    get_config('app.course.level',$value['level']),
                    get_config('app.course.type',$value['type']),
                    $value['days'].'d',
                    get_config('app.course.module',$value['module']),
                    $value['english'] == '' ? '':get_config('app.course.english', $value['english']),
                    $value['target_audience'],
                    $value['description'],
                    $value['e_description'],
                    $value['seminar_owner'],
                    $value['prerequisite'],
                    $recommendation
                ];
                fputcsv($fp, $arr);
            }
            flush();
        }
    }


    //可见范围
    public function recommend(Request $request)
    {
        $courseid = $request->get('courseid');
        $type = $request->get('type');

        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }


    public function getRecommendList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['b.name|b.userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        $where[] = ['a.courseid', '=', $get['courseid']];
        $where[] = ['a.recommend_type', '=', $get['type']];

        $total = Db::table('o_course_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid')
            ->where($where)
            ->group('a.userid')
            ->count();

        $rows = Db::table('o_course_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid')
            ->where($where)
            ->field('a.id, a.type, b.name, b.userid, b.department_name, b.division, b.position, b.in_time')
            ->group('a.userid')
            ->order('a.id desc')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['carolid'] = '00'.$v['userid'];
                } else {
                    $v['carolid'] = $v['userid'];
                }
            } else {
                $v['carolid'] = $v['userid'];
            }

            $where = array(
                'courseid' => $get['courseid'],
                'userid' => $v['userid'],
                'type' => 1,
                'recommend_type' => $get['type']
            );
            $res = Db::name('course_user')->where($where)->find();
            if ($res) {
                $v['type'] = 1;
            } else {
                $v['type'] = 2;
            }
            if ($v['in_time'] != '') {
                $v['in_time'] = date('Y-m-d H:i',$v['in_time']);
            } else {
                $v['in_time'] = '-------';
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);

    }

    // 学员
    public function members(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }


    // 学员
    public function members1(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }

    //+员工数据加载
    public function getUserLoad(Request $request) {

        $get = $request->get();

        $field = 'id';
        $sort = 'asc';
        $where = [];

        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',a.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['role'])) {
            if (!empty($get['role'])) {
                $where[] = ['a.role', '=', $get['role']];
            }
        }


        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['a.name|a.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['a.status', '<>', 3];


        $total = Db::table('o_members')
            ->alias('a')
            ->where($where)
            ->count();


        $rows = Db::table('o_members')
            ->alias('a')
            ->where($where)
            ->field('a.*')
            ->order("$field $sort")
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['carolid'] = '00'.$v['userid'];
                } else {
                    $v['carolid'] = $v['userid'];
                }
            } else {
                $v['carolid'] = $v['userid'];
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function getUserLoad1(Request $request) {

        $get = $request->get();
        $where = [];


        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['b.status', '<>', 3];

        $where[] = ['a.courseid', '=', $get['courseid']];
        $where[] = ['a.recommend_type', '=', 1];


        $total = Db::table('o_course_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid')
            ->where($where)
            ->group('a.userid')
            ->count();

        $rows = Db::table('o_course_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid')
            ->where($where)
            ->field('a.id, a.type, b.name, b.userid, b.department_name, b.position, b.in_time')
            ->group('a.userid')
            ->order('a.id desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();


        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['carolid'] = '00'.$v['userid'];
                } else {
                    $v['carolid'] = $v['userid'];
                }
            } else {
                $v['carolid'] = $v['userid'];
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function saveMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $userid = $request->post('userid');
        $courseid = $request->post('courseid');
        $type = $request->post('type');

        if (empty($userid) || empty($courseid)) {
            return $this->outputAjax('参数缺失');
        }

        Db::startTrans();
        try {
            $ids = explode(',', $userid);

            foreach ($ids as &$v) {
                $res = Db::name('course_user')
                    ->where('userid', '=', $v)
                    ->where('courseid', '=', $courseid)
                    ->where('type', '=', 2)
                    ->where('recommend_type', '=', $type)
                    ->find();
                if ($res) {
                    $name = Db::name('members')->where(array('userid'=>$v))->value('name');
                    Db::rollback();
                    return $this->outputAjax($name.'已选择');
                }

                $insert = array(
                    'courseid' => $courseid,
                    'userid' => $v,
                    'rules_id' => 0,
                    'type' => 2,
                    'recommend_type' => $type,
                    'add_time' => time()
                );
                if (!Db::name('course_user')->insert($insert)) {
                    Db::rollback();
                    return $this->outputAjax('保存失败');
                }
            }

            Db::commit();
            return $this->outputAjax('保存成功', 0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    //+删除学员
    public function recommendDeleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        $courseid = $request->post('courseid');
        $type = $request->post('type');

        if (empty($id)) {
            return $this->outputAjax('参数缺失！');
        }

        Db::startTrans();
        try {
            $ids = explode(',', $id);

            $arr = [];
            foreach ($ids as &$v) {
                $inf = Db::name('course_user')->where('id', '=', $v)->find();

                $res = Db::name('course_user')
                    ->where('courseid', '=', $inf['courseid'])
                    ->where('userid', '=', $inf['userid'])
                    ->where('type', '=', 1)
                    ->where('recommend_type', '=', $type)
                    ->find();
                if ($res) {
                    array_push($arr, $inf['userid']);
                }

                if (!empty($arr)) {
                    $user_list = Db::name('members')->where('userid','in', $arr)->column('name');
                    return $this->outputAjax(implode('、',$user_list).'规则推荐下学员不可删除！');
                }
            }


            $userid = Db::name('course_user')->where('id', 'in', $id)->column('userid');
            if (!Db::name('course_user')->where('id', 'in', $ids)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败！');
            }
            if ($type == 1) {
                $soft_user = Db::name('course_user')
                    ->where('courseid', '=', $courseid)
                    ->where('recommend_type', '=', 2)
                    ->where('userid', 'in', $userid)
                    ->select()->toArray();
                if (!empty($soft_user)) {
                    if (!Db::name('course_user')
                        ->where('courseid', '=', $courseid)
                        ->where('recommend_type', '=', 2)
                        ->where('userid', 'in', $userid)
                        ->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[1]');
                    }
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！',0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    //文件批量导入学员
    public function importUser(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }

    public function executeImportUser(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $type = $request->param('type');
        $courseid = $request->param('courseid');

        if(empty($courseid) || empty($type)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $course = Db::name('course')->where('courseid', '=', $courseid)->find();
        if(!$course) {
            return $this->outputAjax('课程不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];
                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid, language, name')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('course_user')
                    ->where('userid', '=', $userid)
                    ->where('courseid', '=', $course['courseid'])
                    ->where('type', '=', 2)
                    ->where('recommend_type', '=', $type)
                    ->find();
                if($res) {
                    continue;
                }

                $newValue = [
                    'courseid' => $course['courseid'],
                    'userid' => $user['userid'],
                    'rules_id' => 0,
                    'type' => 2,
                    'recommend_type' => $type,
                    'add_time' => time()
                ];
                $f = Db::name('course_user')->insert($newValue);
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }

    //文件批量删除学员
    public function deleteUser(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }

    public function executeDeleteUser(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $type = $request->param('type');
        $courseid = $request->param('courseid');

        if(empty($courseid) || empty($type)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $course = Db::name('course')->where('courseid', '=', $courseid)->find();
        if(!$course) {
            return $this->outputAjax('课程不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];
                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid, language, name')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('course_user')
                    ->where('userid', '=', $userid)
                    ->where('courseid', '=', $course['courseid'])
                    ->where('type', '=', 2)
                    ->where('recommend_type', '=', $type)
                    ->find();
                if(!$res) {
                    continue;
                }

                $where = [];
                $where[] = ['courseid', '=', $course['courseid']];
                $where[] = ['userid', '=', $user['userid']];
                $where[] = ['type', '=', 2];
                $where[] = ['recommend_type', '=', $type];
                $f = Db::name('course_user')->where($where)->delete();
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('删除成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }



    // 导出软硬推荐下学员
    public function exportUser(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $get = $request->get();

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');
        if ($get['type'] == 1) {
            $fileName = '可见范围下学员' . date('Ymd', time());
        } else {
            $fileName = '软推荐学员' . date('Ymd', time());
        }

        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['ID', '工号', '姓名', 'Division', '部门', '职务', '入职时间']);

        $where = [];

        if (!empty($get['keys'])) {
            $where[] = ['b.name|a.userid', 'like', '%'.$get['keys'].'%'];
        }

        $where[] = ['a.courseid', '=', $get['courseid']];
        $where[] = ['a.recommend_type', '=', $get['type']];

        $total = Db::name('course_user')
            ->alias('a')
            ->join('o_members b','a.userid=b.userid', 'left')
            ->where($where)
            ->group('a.userid')
            ->count();

        $nums = 1000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::name('course_user')
                ->alias('a')
                ->join('o_members b','a.userid=b.userid', 'left')
                ->where($where)
                ->group('a.userid')
                ->field('a.id, a.type, b.name, a.userid, b.department_name, b.division, b.position, b.in_time')
                ->order('a.id', 'desc')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {
                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $carolid = "'00".$v['userid'];
                    } else {
                        $carolid = $v['userid'];
                    }
                } else {
                    $carolid = $v['userid'];
                }

                $where1 = [
                    ['courseid', '=', $get['courseid']],
                    ['userid', '=', $v['userid']],
                    ['type', '=', 1],
                    ['recommend_type', '=', $get['type']]
                ];
                $res = Db::name('course_user')->where($where1)->find();
                if ($res) {
                    $type = '规则推荐学员';
                } else {
                    $type = '直选';
                }
                if ($v['in_time'] != '') {
                    $in_time = date('Y-m-d H:i',$v['in_time']);
                } else {
                    $in_time = '-------';
                }

                $arr = [
                    $v['id'],
                    $carolid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['position'],
                    $in_time,
                    $type
                ];
                fputcsv($fp, $arr);
            }
            ob_flush();
            flush();
        }
    }

    //规则
    public function rule(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }


    public function getRuleList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];
        $where[] = ['courseid', '=', $get['courseid']];
        $where[] = ['type', '=', $get['type']];

        $total = Db::name('course_rules')
            ->where($where)
            ->count();

        $rows = Db::name('course_rules')
            ->where($where)
            ->field('id, name, add_time, courseid')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $v['num'] = Db::name('course_user')->where('rules_id', '=', $v['id'])->count();
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function addRule(Request $request)
    {
        $courseid = $request->param('courseid');
        $type = $request->param('type');
        View::assign('courseid', $courseid);
        View::assign('type', $type);
        return View::fetch();
    }



    public function showField(Request $request)
    {
        $field = $request->get('type');
        $courseid = $request->get('courseid');
        $rule_id = $request->get('rule_id');

        View::assign('field', $field);
        View::assign('courseid', $courseid);
        View::assign('rule_id', $rule_id);
        return View::fetch();
    }

    public function getshowField(Request $request)
    {
        $field = $request->post('type');
        $courseid = $request->post('courseid');
        $rule_id = $request->post('rule_id');

        if (!empty($courseid) && !empty($rule_id)) {
            $s_str = Db::name('course_rules')
                ->where('courseid', '=', $courseid)
                ->where('id', '=', $rule_id)
                ->value($field);
            if (empty($s_str)) {
                $s_str = [];
            } else {
                $s_str = explode(',', $s_str);
            }
        } else {
            $s_str = [];
        }

        $s = Db::name('members')->field($field)->group($field)->select()->toArray();
        $data = [];
        foreach ($s as &$v) {
            if($v[$field] == '') {
                continue;
            }
            $arr = array(
                'title' => $v[$field],
                'value' => $v[$field],
            );
            array_push($data, $arr);
        }
        $data = array(
            'fields' => $data,
            'field' => $field,
            's' => $s_str,
        );

        $datas = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data
        );
        return json($datas);
    }


    // 保存规则
    public function saveRule(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post['name'])) {
            return $this->outputAjax('请填写规则名');
        }
        if (empty($post['function']) && empty($post['position']) && empty($post['division']) && empty($post['division_mt']) && empty($post['entity']) && empty($post['entity_mt']) && empty($post['activity_sector']) && empty($post['department_name']) && empty($post['region']) && empty($post['office_location']) && empty($post['nationality']) && $post['services_year'] != '' && $post['age'] != '' && $post['xiashu'] != '') {
            return $this->outputAjax('请至少选择一项');
        }
        $where = [];

        if (!empty($post['function'])) {
            $where[] = ['function', 'in', $post['function']];
        }

        if (!empty($post['position'])) {
            $where[] = ['position', 'in', $post['position']];
        }
        if (!empty($post['division'])) {
            $where[] = ['division', 'in', $post['division']];
        }
        if (!empty($post['division_mt'])) {
            $where[] = ['division_mt', 'in', $post['division_mt']];
        }
        if (!empty($post['entity'])) {
            $where[] = ['entity', 'in', $post['entity']];
        }

        if (!empty($post['entity_mt'])) {
            $where[] = ['entity_mt', 'in', $post['entity_mt']];
        }

        if (!empty($post['activity_sector'])) {
            $where[] = ['activity_sector', 'in', $post['activity_sector']];
        }

        if (!empty($post['department_name'])) {
            $where[] = ['department_name', 'in', $post['department_name']];
        }
        if (!empty($post['region'])) {
            $where[] = ['region', 'in', $post['region']];
        }
        if (!empty($post['office_location'])) {
            $where[] = ['office_location', 'in', $post['office_location']];
        }

        if (!empty($post['nationality'])) {
            $where[] = ['nationality', 'in', $post['nationality']];
        }

        if (!empty($post['age'])) {
            $where[] = ['age', trim($post['age_select']), $post['age']];
        }

        if (!empty($post['services_year'])) {
            $where[] = ['services_year', trim($post['services_year_select']), $post['services_year']];
        }

        if (!empty($post['xiashu'])) {
            $where[] = ['xiashu', trim($post['xiashu_select']), $post['xiashu']];
        }

        $where[] = ['status', '=', 1];

        $user = Db::name('members')->where($where)->column('userid');
        if (empty($user)) {
            return $this->outputAjax('暂无匹配学员');
        }

        Db::startTrans();
        try {
            $insert = array(
                'courseid' => $post['courseid'],
                'type' => $post['type'],
                'name' => $post['name'],
                'function' => $post['function'],
                'position' => $post['position'],
                'division' => $post['division'],
                'division_mt' => $post['division_mt'],
                'entity' => $post['entity'],
                'entity_mt' => $post['entity_mt'],
                'activity_sector' => $post['activity_sector'],
                'department_name' => $post['department_name'],
                'region' => $post['region'],
                'office_location' => $post['office_location'],
                'nationality' => $post['nationality'],
                'services_year_select' => trim($post['services_year_select']),
                'services_year' => $post['services_year'],
                'age_select' => trim($post['age_select']),
                'age' => $post['age'],
                'xiashu_select' => trim($post['xiashu_select']),
                'xiashu' => $post['xiashu'],
                'add_time' => time()
            );
            $RulesID = Db::name('course_rules')->insertGetId($insert);
            if (!$RulesID) {
                Db::rollback();
                return $this->outputAjax('保存失败');
            }
            $user_array = [];
            foreach ($user as &$v) {
                $arr = array(
                    'courseid' => $post['courseid'],
                    'userid' => $v,
                    'rules_id' => $RulesID,
                    'type' => 1,
                    'recommend_type' => $post['type'],
                    'add_time' => time()
                );
                array_push($user_array, $arr);
            }

            $res = Db::name('course_user')->insertAll($user_array);
            if (!$res) {
                Db::rollback();
                return $this->outputAjax('保存失败[1]');
            }

            Db::commit();
            return $this->outputAjax('保存成功', 0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    //+修改具体规则
    public function editRule(Request $request)
    {
        $id = $request->get('id');

        $inf = Db::name('course_rules')->where('id', '=', $id)->find();
        View::assign('inf', $inf);
        $type = $request->param('type');
        View::assign('type', $type);
        return View::fetch();
    }


    //+修改规则
    public function modifyRules(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post['name'])) {
            return $this->outputAjax('请填写规则名');
        }
        if (empty($post['function']) && empty($post['position']) && empty($post['division']) && empty($post['division_mt']) && empty($post['entity']) && empty($post['entity_mt']) && empty($post['activity_sector']) && empty($post['department_name']) && empty($post['region']) && empty($post['office_location']) && empty($post['nationality']) && $post['services_year'] != '' && $post['age'] != '' && $post['xiashu'] != '') {
            return $this->outputAjax('请至少选择一项');
        }
        $where = [];

        if (!empty($post['function'])) {
            $where[] = ['function', 'in', $post['function']];
        }

        if (!empty($post['position'])) {
            $where[] = ['position', 'in', $post['position']];
        }
        if (!empty($post['division'])) {
            $where[] = ['division', 'in', $post['division']];
        }
        if (!empty($post['division_mt'])) {
            $where[] = ['division_mt', 'in', $post['division_mt']];
        }
        if (!empty($post['entity'])) {
            $where[] = ['entity', 'in', $post['entity']];
        }

        if (!empty($post['entity_mt'])) {
            $where[] = ['entity_mt', 'in', $post['entity_mt']];
        }

        if (!empty($post['activity_sector'])) {
            $where[] = ['activity_sector', 'in', $post['activity_sector']];
        }

        if (!empty($post['department_name'])) {
            $where[] = ['department_name', 'in', $post['department_name']];
        }
        if (!empty($post['region'])) {
            $where[] = ['region', 'in', $post['region']];
        }
        if (!empty($post['office_location'])) {
            $where[] = ['office_location', 'in', $post['office_location']];
        }

        if (!empty($post['nationality'])) {
            $where[] = ['nationality', 'in', $post['nationality']];
        }

        if (!empty($post['age'])) {
            $where[] = ['age', trim($post['age_select']), $post['age']];
        }

        if (!empty($post['services_year'])) {
            $where[] = ['services_year', trim($post['services_year_select']), $post['services_year']];
        }

        if (!empty($post['xiashu'])) {
            $where[] = ['xiashu', trim($post['xiashu_select']), $post['xiashu']];
        }

        $where[] = ['status', '=', 1];

        $user = Db::name('members')->where($where)->column('userid');
        if (empty($user)) {
            return $this->outputAjax('暂无匹配学员');
        }

        Db::startTrans();
        try {
            $update = array(
                'id' => $post['id'],
                'name' => $post['name'],
                'function' => $post['function'],
                'position' => $post['position'],
                'division' => $post['division'],
                'division_mt' => $post['division_mt'],
                'entity' => $post['entity'],
                'entity_mt' => $post['entity_mt'],
                'activity_sector' => $post['activity_sector'],
                'department_name' => $post['department_name'],
                'region' => $post['region'],
                'office_location' => $post['office_location'],
                'nationality' => $post['nationality'],
                'services_year_select' => trim($post['services_year_select']),
                'services_year' => $post['services_year'],
                'age_select' => trim($post['age_select']),
                'age' => $post['age'],
                'xiashu_select' => trim($post['xiashu_select']),
                'xiashu' => $post['xiashu'],
                'update_time' => time()
            );
            if (!Db::name('course_rules')->update($update)) {
                Db::rollback();
                return $this->outputAjax('保存失败');
            }

            $old = Db::name('course_user')->where('rules_id', '=', $post['id'])->column('userid');

            $new = array_diff($user, $old);
            $old_user = array_diff($old, $user);
            $user_array = [];
            if (!empty($new)) {
                foreach ($new as &$v) {
                    $arr = array(
                        'courseid' => $post['courseid'],
                        'rules_id' => $post['id'],
                        'userid' => $v,
                        'type' => 1,
                        'recommend_type' => $post['type'],
                        'add_time' => time()
                    );
                    array_push($user_array, $arr);
                }

                $res = Db::name('course_user')->insertAll($user_array);
                if (!$res) {
                    Db::rollback();
                    return $this->outputAjax('保存失败[1]');
                }
            }
            if (!empty($old_user)) {
                if (!Db::name('course_user')
                    ->where('rules_id', '=', $post['id'])
                    ->where('userid', 'in', $old_user)
                    ->where('type', '=', 1)
                    ->delete()){
                    Db::rollback();
                    return $this->outputAjax('保存失败[2]');
                }
            }
            if ($post['type'] == 1) {
                $arr = [];
                foreach($old_user as &$v) {
                    $count = Db::name('course_user')
                        ->where('courseid', '=', $post['courseid'])
                        ->where('userid', '=', $v)
                        ->where('recommend_type', '=', 1)
                        ->count();
                    if ($count == 1) {
                        array_push($arr, $v);
                    }
                }

                $soft = Db::name('course_user')
                    ->where('courseid', '=', $post['courseid'])
                    ->where('userid', 'in', $arr)
                    ->where('recommend_type', '=', 2)
                    ->find();
                if ($soft) {
                    if (!Db::name('course_user')
                        ->where('courseid', '=', $post['courseid'])
                        ->where('userid', 'in', $arr)
                        ->where('recommend_type', '=', 2)
                        ->delete()){
                        Db::rollback();
                        return $this->outputAjax('保存失败[3]');
                    }
                }
            }

            Db::commit();
            return $this->outputAjax('保存成功', 0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    //+删除规则
    public function deleteRules(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        if (empty($id)) {
            return $this->outputAjax('参数缺失！');
        }

        Db::startTrans();
        try {

            $rule = Db::name('course_rules')->where('id', '=', $id)->find();

            if (!Db::name('course_rules')->where('id', '=', $id)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败！');
            }
            $res = Db::name('course_user')->where('rules_id', '=', $id)->find();
            if ($res) {
                if ($rule['type'] == 1) {
                    $userid = Db::name('course_user')->where('rules_id', '=', $id)->column('userid');
                    $arr = [];
                    foreach($userid as &$val) {
                        $count = Db::name('course_user')
                            ->where('courseid', '=', $res['courseid'])
                            ->where('userid', '=', $val)
                            ->where('recommend_type', '=', 1)
                            ->count();
                        if ($count == 1) {
                            array_push($arr, $val);
                        }
                    }
                }

                if (!Db::name('course_user')->where('rules_id', '=', $id)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]！');
                }

                if ($rule['type'] == 1) {
                    $soft = Db::name('course_user')
                        ->where('courseid', '=', $res['courseid'])
                        ->where('userid', 'in', $arr)
                        ->where('recommend_type', '=', 2)
                        ->find();
                    if ($soft) {
                        if (!Db::name('course_user')
                            ->where('courseid', '=', $res['courseid'])
                            ->where('userid', 'in', $arr)
                            ->where('recommend_type', '=', 2)
                            ->delete()) {
                            Db::rollback();
                            return $this->outputAjax('删除失败[2]！');
                        }
                    }
                }
            }
            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }



    //+刷新规则
    public function refreshRules(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $rules_id = $request->post('id');

        if (empty($rules_id)) {
            return $this->outputAjax('参数缺失！');
        }

        $ids = explode(',', $rules_id);
        Db::startTrans();
        try {
            foreach ($ids as &$v) {
                $inf = Db::name('course_rules')->where('id', '=', $v)->find();
                if (empty($inf)) {
                    Db::rollback();
                    return $this->outputAjax('参数错误');
                }

                $where = [];

                if (!empty($inf['function'])) {
                    $where[] = ['function', 'in', $inf['function']];
                }

                if (!empty($inf['position'])) {
                    $where[] = ['position', 'in', $inf['position']];
                }
                if (!empty($inf['division'])) {
                    $where[] = ['division', 'in', $inf['division']];
                }
                if (!empty($inf['division_mt'])) {
                    $where[] = ['division_mt', 'in', $inf['division_mt']];
                }
                if (!empty($inf['entity'])) {
                    $where[] = ['entity', 'in', $inf['entity']];
                }

                if (!empty($inf['entity_mt'])) {
                    $where[] = ['entity_mt', 'in', $inf['entity_mt']];
                }

                if (!empty($inf['activity_sector'])) {
                    $where[] = ['activity_sector', 'in', $inf['activity_sector']];
                }

                if (!empty($inf['department_name'])) {
                    $where[] = ['department_name', 'in', $inf['department_name']];
                }
                if (!empty($inf['region'])) {
                    $where[] = ['region', 'in', $inf['region']];
                }
                if (!empty($inf['office_location'])) {
                    $where[] = ['office_location', 'in', $inf['office_location']];
                }

                if (!empty($inf['nationality'])) {
                    $where[] = ['nationality', 'in', $inf['nationality']];
                }

                if (!empty($inf['age'])) {
                    $where[] = ['age', trim($inf['age_select']), $inf['age']];
                }

                if (!empty($inf['services_year'])) {
                    $where[] = ['services_year', trim($inf['services_year_select']), $inf['services_year']];
                }

                if (!empty($inf['xiashu'])) {
                    $where[] = ['xiashu', trim($inf['xiashu_select']), $inf['xiashu']];
                }

                $where[] = ['status', '=', 1];

                $user = Db::name('members')->where($where)->column('userid');
                if (empty($user)) {
                    Db::rollback();
                    return $this->outputAjax('暂无匹配学员');
                }


                $old = Db::name('course_user')->where('rules_id', '=', $v)->column('userid');

                $new = array_diff($user, $old);
                $old_user = array_diff($old, $user);
                $user_array = [];
                if (!empty($new)) {
                    foreach ($new as &$v) {
                        $arr = array(
                            'courseid' => $inf['courseid'],
                            'rules_id' => $inf['id'],
                            'userid' => $v,
                            'type' => 1,
                            'recommend_type' => $inf['type'],
                            'add_time' => time()
                        );
                        array_push($user_array, $arr);
                    }

                    $res = Db::name('course_user')->insertAll($user_array);
                    if (!$res) {
                        Db::rollback();
                        return $this->outputAjax('保存失败[1]');
                    }
                }
                if (!empty($old_user)) {
                    if (!Db::name('course_user')
                        ->where('rules_id', '=', $inf['id'])
                        ->where('userid', 'in', $old_user)
                        ->where('type', '=', 1)
                        ->delete()){
                        Db::rollback();
                        return $this->outputAjax('保存失败[2]');
                    }
                }
                if ($inf['type'] == 1) {
                    $arr = [];
                    foreach($old_user as &$v) {
                        $count = Db::name('course_user')
                            ->where('courseid', '=', $inf['courseid'])
                            ->where('userid', '=', $v)
                            ->where('recommend_type', '=', 1)
                            ->count();
                        if ($count == 1) {
                            array_push($arr, $v);
                        }
                    }

                    $soft = Db::name('course_user')
                        ->where('courseid', '=', $inf['courseid'])
                        ->where('userid', 'in', $arr)
                        ->where('recommend_type', '=', 2)
                        ->find();
                    if ($soft) {
                        if (!Db::name('course_user')
                            ->where('courseid', '=', $inf['courseid'])
                            ->where('userid', 'in', $arr)
                            ->where('recommend_type', '=', 2)
                            ->delete()){
                            Db::rollback();
                            return $this->outputAjax('保存失败[3]');
                        }
                    }
                }

                Db::commit();
                return $this->outputAjax('刷新成功', 0);
            }
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }

    }

    //+复制规则
    public function copyRule(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $rules_id = $request->post('id');

        if (empty($rules_id)) {
            return $this->outputAjax('参数缺失！');
        }

        $ids = explode(',', $rules_id);
        Db::startTrans();
        try {
            foreach ($ids as &$v) {
                $inf = Db::name('course_rules')->where('id', '=', $v)->find();
                $insert = array(
                    'courseid' => $inf['courseid'],
                    'type' => $inf['type'],
                    'name' => $inf['name'],
                    'function' => $inf['function'],
                    'position' => $inf['position'],
                    'division' => $inf['division'],
                    'division_mt' => $inf['division_mt'],
                    'entity' => $inf['entity'],
                    'entity_mt' => $inf['entity_mt'],
                    'activity_sector' => $inf['activity_sector'],
                    'department_name' => $inf['department_name'],
                    'region' => $inf['region'],
                    'office_location' => $inf['office_location'],
                    'nationality' => $inf['nationality'],
                    'services_year_select' => trim($inf['services_year_select']),
                    'services_year' => $inf['services_year'],
                    'age_select' => trim($inf['age_select']),
                    'age' => $inf['age'],
                    'xiashu_select' => trim($inf['xiashu_select']),
                    'xiashu' => $inf['xiashu'],
                    'add_time' => time()
                );
                $RulesID = Db::name('course_rules')->insertGetId($insert);
                if (!$RulesID) {
                    Db::rollback();
                    return $this->outputAjax('复制失败');
                }
                $user = Db::name('course_user')->where('rules_id', '=', $v)->column('userid');
                $user_array = [];
                foreach ($user as &$val) {
                    $arr = array(
                        'courseid' => $inf['courseid'],
                        'userid' => $val,
                        'rules_id' => $RulesID,
                        'type' => 1,
                        'recommend_type' => $inf['type'],
                        'add_time' => time()
                    );
                    array_push($user_array, $arr);
                }

                $res = Db::name('course_user')->insertAll($user_array);
                if (!$res) {
                    Db::rollback();
                    return $this->outputAjax('复制失败[1]');
                }
            }

            Db::commit();
            return $this->outputAjax('复制成功', 0);
        }  catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }
}